﻿myApp.controller("homeLoanCalculatorController", function ($scope, modalService) {
    document.title = "Penang Realty BUY OR RENT WITH US 世界地產 HomeLoan Calculator";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty BUY OR RENT WITH US 世界地產 HomeLoan Calculator', 'description': 'Free online home loan calculator. Try it now.' });
    $scope.purchasePrice = 600000;
    $scope.marginFinance = 90;
    $scope.loanAmount = $scope.purchasePrice * $scope.marginFinance / 100;
    $scope.interestRate = 5;
    $scope.tenure = 30;
    $scope.mrta = 0;
    $scope.others = 0;
    $scope.total = $scope.loanAmount + $scope.mrta + $scope.others;

   $scope.calculate =  function ()
    {

        var purchase_price = $scope.purchasePrice;
        var margin_finance = $scope.marginFinance;
        var loan_amount = purchase_price * margin_finance / 100;


        $scope.total= $scope.loanAmount + $scope.mrta + $scope.others;
        var total_loan_amount = $scope.total;       
        $scope.total_months = $scope.tenure * 12;
        var r = $scope.interestRate / (12 * 100);
        var p = (total_loan_amount * r * Math.pow((1 + r), $scope.total_months)) / (Math.pow((1 + r), $scope.total_months) - 1);
        var prin = Math.round(p * 100) / 100;
        $scope.monthlyPayment = prin;      
        var mon = Math.round((($scope.total_months * prin) - total_loan_amount) * 100) / 100;
        $scope.totalInterest = mon;
        var tot = Math.round((mon / $scope.total_months) * 100) / 100;
        $scope.monthlyInterest = tot;
        $scope.totalPayment = Math.round(prin * $scope.total_months);

      
    }
    $scope.generateTable = function () {
        $scope.calculate();
        $scope.calc = true;
        //var total_months = $("#txtTenure").val() * 12;
        //var total_payment = $("#txtTotalPayment").val();
        //var monthly_payment = $("#txtMonthlyPayment").val();
        //var monthly_interest = $("#txtMonthlyIntest").val();
        //var total_loan_amount = $("#txtTotal").val();
        var monthly_principle = $scope.monthlyPayment - $scope.monthlyInterest;
        var loan_balance = $scope.totalPayment;
        var monthly_principle_balance = $scope.total;

        $scope.payments = [];
     
        for (var i = 1; i <= $scope.total_months; i++) {
            loan_balance = loan_balance - $scope.monthlyPayment;
            monthly_principle_balance = monthly_principle_balance - monthly_principle;
            $scope.payments[i] = { month: i, loan_balance: loan_balance, monthly_principle_balance: monthly_principle_balance, monthly_interest: $scope.monthlyInterest };
            
        }
      

    }

    function pageInit()
    {
        $scope.calculate();
    }
    pageInit();

})